<template>
  <a-form ref="formRef" class="login-form-wrapper" layout="vertical" :model="form" :rules="rules">
    <div class="login-form-title">警务督察管理系统登录</div>
    <a-form-item field="userName" validate-trigger="blur" hide-label>
      <a-input v-model="form.userName" autocomplete="userName" placeholder="admin">
        <template #prefix>
          <icon-user />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item field="policeNum" validate-trigger="blur" hide-label>
      <a-input v-model="form.policeNum" autocomplete="police-number" placeholder="001" allow-clear>
        <template #prefix>
          <icon-idcard />
        </template>
      </a-input>
    </a-form-item>
    <a-checkbox checked="rememberPassword" :model-value="loginConfig.rememberPassword" @change="setRememberPassword">
      记住登录信息
    </a-checkbox>
    <a-button type="primary" style="margin: 32px 0 6px" long :loading="loading" @click="handleSubmit"> 登录 </a-button>
  </a-form>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { useStorage } from '@vueuse/core';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/useLoading';
  import type { LoginData } from '@/api/user';
  import { pick } from 'lodash';
  import { Message } from '@arco-design/web-vue';
  import { formatDynamicRoutes, addDynamicRoutes } from '@/utils/dynamic-routes';
  import { setToken } from '@/utils/auth';

  const router = useRouter();
  const userStore = useUserStore();
  const formRef = ref();
  const { loading, setLoading } = useLoading();

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    userName: 'admin', // 测试默认用户名
    policeNum: '001' // 测试默认警号
  });
  const form = reactive({
    userName: 'admin', // 直接显示默认用户名
    policeNum: '001' // 直接显示默认警号
  });

  const rules = {
    userName: [{ required: true, message: '请输入用户名' }],
    policeNum: [{ required: true, message: '请输入警号' }]
  };

  const handleSubmit = () => {
    if (loading.value) return;

    formRef.value.validateField(['userName', 'policeNum']).then(async res => {
      if (res) return;
      setLoading(true);
      try {
        const userInfoForm = pick(form, ['userName', 'policeNum']);
        console.log('登录请求数据:', userInfoForm);

        const loginResponse = await userStore.login(userInfoForm as LoginData);
        console.log('登录响应:', loginResponse);

        // 检查后端返回的状态码
        if (loginResponse.code === 200 || loginResponse.code === 0) {
          // 登录成功
          Message.success('登录成功');

          // 1. 保存token
          setToken((loginResponse.data as any).token);

          // 2. 字段映射，设置用户信息
          const { token, userName, roleId, groupId, groupName, ...rest } = loginResponse.data as any;
          userStore.info({
            name: userName,
            role: roleId,
            group: groupId,
            groupName: groupName,
            ...rest
          });

          // 获取用户菜单权限
          const menus = await userStore.getFuncMenus();

          // 如果有菜单权限则注册路由
          if (menus && menus.length > 0) {
            const dynamicRoutes = formatDynamicRoutes(menus);
            addDynamicRoutes(dynamicRoutes);

            // 检查特定路由是否存在
            const checkRoutes = ['Home', 'Workplace', 'daily', 'NoticeDaily', 'timeLimitedTask', 'NoticeSelfCheck'];

            checkRoutes.forEach(routeName => {
              const exists = router.hasRoute(routeName);
              if (exists) {
                const route = router.getRoutes().find(r => r.name === routeName);
              }
            });
          } else {
            console.warn('没有获取到功能菜单数据');
          }

          const { redirect, ...othersQuery } = router.currentRoute.value.query;
          if (redirect) {
            // 如果有重定向参数，直接跳转到指定路径
            router.push(redirect as string);
          } else {
            // 否则跳转到首页 - 尝试多个可能的路径
            const possibleRoutes = ['Workplace', 'dashboard', '/dashboard'];
            let targetRoute = null;

            for (const routeName of possibleRoutes) {
              if (router.hasRoute(routeName)) {
                targetRoute = { name: routeName };
                break;
              }
            }

            if (!targetRoute) {
              // 如果都找不到，使用路径跳转
              targetRoute = { path: '/dashboard' };
            }

            router.push({
              ...targetRoute,
              query: {
                ...othersQuery
              }
            });
          }

          // const { rememberPassword } = loginConfig.value;
          // const { userName: loginUserName, policeNum } = userInfoForm;
          // // 实际生产环境需要进行加密存储。
          // loginConfig.value.userName = rememberPassword ? loginUserName : '';
          // loginConfig.value.policeNum = rememberPassword ? policeNum : '';
        } else {
          // 登录失败，显示后端返回的错误信息
          Message.error(loginResponse.message || '登录失败，请检查用户名和警号');
        }
      } catch (error) {
        console.error('登录错误:', error);
      } finally {
        setLoading(false);
      }
    });
  };

  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 330px;
      padding: 24px 24px 12px;
      overflow: hidden;
      background-color: var(--color-bg-1);
      border: 1px solid var(--color-border-2);
      border-radius: var(--border-radius-large);
    }

    &-title {
      margin-bottom: 16px;
      font-size: 24px;
      font-weight: 500;
      line-height: 32px;
      color: var(--color-text-1);
    }
  }
</style>
